package com.cxg.fairy.ec.main.order;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.ec.main.personal.order.OrderListEntryDelegate;
import com.cxg.fairy.ec.pay.FastPay;
import com.cxg.fairy.ec.pay.IAlPayResultListener;
import com.cxg.fairy.ec.pay.status.PayStatusDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.widget.CheckBox.CheckBoxGType;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.mylhyl.superdialog.SuperDialog;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/4/23.
 */

public class CheckPayDelegate extends LatteDelegate  implements ISuccess{

    private int PAYTYPE = 0;

    private String amount = "0";

    private int balance = 0;

    private boolean isDeposit = false;

    private String orderNo = "";

    private void setPayType(int i) {
        this.PAYTYPE = i;
    }

    private int getPayType() {
        return this.PAYTYPE;
    }

    private static final RequestOptions OPTIONS = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .centerCrop()
            .dontAnimate();

    public CheckPayDelegate setAmount(String amount) {
        this.amount = amount;
        return this;
    }

    public CheckPayDelegate setIsDeposit(boolean mIsDeposit) {
        this.isDeposit = mIsDeposit;
        return this;
    }

    public CheckPayDelegate setOrderNo(String mOrderNo) {
        this.orderNo = mOrderNo;
        return this;
    }

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
        initSdialog();
    }

    @BindView(R2.id.aci_check_pay_banner)
    AppCompatImageView ivPayBanner = null;

    @BindView(R2.id.checkBoxALIPAY)
    CheckBoxGType checkBoxALIPAY = null;

    @BindView(R2.id.checkBoxGWXPAY)
    CheckBoxGType checkBoxWXPAY = null;

    @BindView(R2.id.checkBoxGYuEPAY)
    CheckBoxGType checkBoxYuEPay = null;

    @BindView(R2.id.ll_check_pay_alipay)
    LinearLayoutCompat lCheckPayAlipay = null;

    @BindView(R2.id.ll_check_pay_wxpay)
    LinearLayoutCompat lCheckPayWxpay = null;

    @BindView(R2.id.ll_check_pay_yupay)
    LinearLayoutCompat lCheckPayYuEPay = null;

    @BindView(R2.id.check_pay_amount)
    AppCompatTextView checkPayAmount = null;

    @BindView(R2.id.ll_check_pay_yue)
    LinearLayout llCheckPayYuE = null;

    @OnClick(R2.id.act_fix_pay)
    void onClickToPay() {

        String dialogPayType = getPayType() == 0 ? "支付宝" : (getPayType() == 1 ? "微信支付" : "余额支付");

        String dialogContent = "支付金额：¥" + amount + "\n支付方式：" + dialogPayType;

        String dialogContents = "支付金额：¥" + amount + "\n帐户余额：¥"+ balance + "\n支付方式：" + dialogPayType;

        String actDiaContent = getPayType() == 2 ? dialogContents : dialogContent;

        int[] padding = new int[4];
        padding[0] =0;padding[1] =0;padding[2] =0;padding[3] =0;

        new SuperDialog.Builder(this.getActivity())
                .setRadius(10)
                .setAlpha(0.9f)
                .setWidth(0.6f)
                .setTitle("支付信息", 40, 80)
                .setMessage(actDiaContent, Color.parseColor("#545454"), 40,padding)
                .setPositiveButton("去支付", new SuperDialog.OnClickPositiveListener() {
                    @Override
                    public void onClick(View v) {
                        toPay();
                    }
                }).build();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_check_pay;
    }

    private void toPay() {
        if (getPayType() == 0) {
            FastPay.create(this).setPayResultListener(new IAlPayResultListener() {
                @Override
                public void onPaySuccess() {
                    LatteLogger.e("CheckPayDelegate.paySuccess=","true");
                    Toasty.success(getContext(), "支付宝支付成功！").show();
                    /** createPayStatusDelegate */
                    getSupportDelegate().startWithPop(PayStatusDelegate.create(orderNo));
                }
                @Override
                public void onPaying() {

                }
                @Override
                public void onPayFail() {
                    Toasty.warning(getContext(), "支付失败！").show();
                }
                @Override
                public void onPayCancel() {
                    Toasty.info(getContext(), "支付取消！").show();
                }
                @Override
                public void onPayConnectError() {
                    Toasty.error(getContext(), "支付接口通讯失败！").show();
                }
            }).setOrderId(orderNo).aliPay();
        } else if (getPayType() == 1) {
            FastPay.create(this).setPayResultListener(new IAlPayResultListener() {
                @Override
                public void onPaySuccess() {
                    LatteLogger.e("CheckPayDelegate.paySuccess=","true");
                    Toasty.success(getContext(), "微信支付成功！").show();
                    /** createPayStatusDelegate */
                    getSupportDelegate().startWithPop(PayStatusDelegate.create(orderNo));
                }
                @Override
                public void onPaying() {

                }
                @Override
                public void onPayFail() {
                    Toasty.warning(getContext(), "支付失败！").show();
                }
                @Override
                public void onPayCancel() {
                    Toasty.info(getContext(), "支付取消！").show();
                }
                @Override
                public void onPayConnectError() {
                    Toasty.error(getContext(), "支付接口通讯失败！").show();
                }
            }).setOrderId(orderNo).wxPay();
        } else if (getPayType() == 2) {
            final String yuePrePayUrl = "payByPayType";
            RestClient.builder()
                    .url(yuePrePayUrl)
                    .params("uuid", AccountManager.getSignUUID())
                    .params("orderNo",orderNo)
                    .params("payType",2)
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            LatteLogger.e("response=",response);
                            int code = JSON.parseObject(response).getInteger("code");
                            if (code == 1) {
                                JSONObject obj = JSON.parseObject(response).getJSONObject("data");
                                final String payStatus = obj.getString("payStatus");
                                Toasty.success(getContext(), "余额支付成功!").show();
                                getSupportDelegate().startWithPop(PayStatusDelegate.create(orderNo));
                            }
                        }
                    })
                    .build()
                    .post();
        }
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        RestClient.builder()
                .url("checkoutCounter")
                .loader(getContext())
                .params("uuid", AccountManager.getSignUUID())
                .params("orderNo",orderNo)
                .success(this)
                .build()
                .post();
    }

    @Override
    public boolean onBackPressedSupport() {
        initSdialog();
        return true;
}

    private DialogFragment initSdialog() {
        return new SuperDialog.Builder(this.getActivity())
                .setRadius(10)
                .setAlpha(0.9f)
                .setWidth(0.6f)
                .setTitle("信息", 40, 80)
                .setMessage("确认离开收银台?", Color.parseColor("#545454"), 40)
                .setPositiveButton("确认离开", new SuperDialog.OnClickPositiveListener() {
                    @Override
                    public void onClick(View v) {
                        if (getParentDelegate() != null) {
                            getParentDelegate().getSupportDelegate().pop();
                        } else {
                            getSupportDelegate().pop();
                        }

                        if (isDeposit == true) {
                            //getSupportDelegate().pop();
                        } else {
                            //getSupportDelegate().startWithPop(new OrderListEntryDelegate());
                        }
                    }
                })
                .setNegativeButton("继续支付", null)
                .build();
    }

    @Override
    public void onSuccess(String response) {
        JSONObject obj = JSON.parseObject(response);
        LatteLogger.e("response", response);
        int code = obj.getInteger("code");
        JSONObject dataObj = obj.getJSONObject("data");
        if (code == 1) {
            if (dataObj.getBoolean("isBpVisible")){
                balance = dataObj.getInteger("balance");
            }
            String imgUrl = dataObj.getString("checkPayBanner");
            String mAmount = dataObj.getString("amount");
            this.setAmount(mAmount);
            checkPayAmount.setText(mAmount);

            if (isDeposit == true) {
                lCheckPayYuEPay.setVisibility(View.INVISIBLE);
                llCheckPayYuE.setVisibility(View.INVISIBLE);
            }
            Glide.with(getContext())
                    .load(imgUrl)
                    .apply(OPTIONS)
                    .into(ivPayBanner);
            checkBoxALIPAY.setChecked(true);

            lCheckPayAlipay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setPayType(0);
                    if (checkBoxALIPAY.isChecked()) {

                    } else {
                        checkBoxALIPAY.setChecked(true);
                        checkBoxWXPAY.setChecked(false);
                        checkBoxYuEPay.setChecked(false);
                    }
                }
            });

            lCheckPayWxpay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setPayType(1);
                    if (checkBoxWXPAY.isChecked()) {

                    } else {
                        checkBoxALIPAY.setChecked(false);
                        checkBoxYuEPay.setChecked(false);
                        checkBoxWXPAY.setChecked(true);
                    }
                }
            });

            lCheckPayYuEPay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setPayType(2);
                    if (checkBoxYuEPay.isChecked()) {

                    } else {
                        checkBoxALIPAY.setChecked(false);
                        checkBoxWXPAY.setChecked(false);
                        checkBoxYuEPay.setChecked(true);
                    }
                }
            });
        } else {
            Toasty.error(getContext(),"与服务器通信失败!").show();
        }
    }
}
